import axios from 'axios'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useToken} from '@/store'
import router from '@/router'

const token = useToken()

const api = axios.create()

api.interceptors.request.use(
  (config) => {
    if (token.value) {
      config.headers['X-Token'] = token.value
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    let {code, msg, data} = response.data
    if (!code) {
      ElMessage.error('未返回code')
      return Promise.reject('未返回code')
    }
    if (code === 0) {
      return data
    }
    if (code === 401) {
      ElMessageBox.confirm('您的登录已过期，请重新登录', '提示', {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        router.replace({
          name: 'Login',
          query: {
            ref: encodeURIComponent(window.location.href),
          },
        })
      })
      return Promise.reject(`${code}:${msg}`)
    }
    ElMessage.error(msg)
    return Promise.reject(`${code}:${msg}`)
  },
  (error) => {
    return Promise.reject(error)
  },
)

export default api
